package com.welsy.iter.business
{
	import mx.rpc.Fault;
	import mx.rpc.events.FaultEvent;
	import mx.rpc.events.ResultEvent;
	import mx.rpc.soap.mxml.WebService;	
	import mx.rpc.AbstractOperation;
	import com.adobe.cairngorm.business.ServiceLocator;
	import com.adobe.cairngorm.business.Responder;
	import mx.collections.ArrayCollection;
	import flash.utils.setTimeout;	
	import com.welsy.iter.vo.IterVO;
	import com.welsy.user.model.UserModelLocator;
		

	/**
	 * @version	$Revision: 1.1 $
	 */
	public class GetItersDelegate
	{
		public function GetItersDelegate( responder : Responder )
		{		
			this.service = ServiceLocator.getInstance().getWebService("iterServices") as WebService;
			this.responder = responder;
		}
		
		public function getIters() : void
		{	
			getRealIters();
			
			//demo
			//setTimeout(getFakeResult,1000,"");
		}
						
		private function getRealIters() : void
		{			
			var o:AbstractOperation = service.getOperation("GetAllEditingIter");
			o.arguments.GetAllEditingIterRequest.AuthorID = UserModelLocator.getInstance().authorId;
			o.addEventListener(ResultEvent.RESULT, GetAllEditingIters_onResult);
			o.addEventListener(FaultEvent.FAULT, GetAllEditingIters_onFault);
			service.GetAllEditingIter();			
		}	
		
		private function GetAllEditingIters_onResult(event:ResultEvent):void
		{
			var itersXMLList:XMLList = event.result as XMLList;
			var iters : ArrayCollection = new ArrayCollection();
			iters = parseXMLIters(itersXMLList)						
			responder.onResult(iters);
		}
		
		private function parseXMLIters(list:XMLList):ArrayCollection
		{
			var iters : ArrayCollection = new ArrayCollection();
			var item:XML;

			list = list.descendants(IterQNames.qnIters).children(); 
			for each(item in list) { 				         	
            	var iterVO:IterVO = new IterVO;
				iterVO.setProperties(item);
				iters.addItem(iterVO);            	            	
   			}
   			return iters;
		}
		
		private function GetAllEditingIters_onFault(event:FaultEvent):void
		{	
			responder.onFault();		
		}
		
		private function getFakeResult(value:String): void
		{			
			var myAC : ArrayCollection = new ArrayCollection();
			var i:int;
			for (i = 0; i < 5; i++) {    
				var iterVO:IterVO = new IterVO;
				iterVO.id = i;
				iterVO.title = "iter"+i;
				myAC.addItemAt(iterVO, i);
			}
						
			if( 1 )
			{
				responder.onResult( myAC );
			}
			else
			{
				responder.onFault();
			}			
		}	
	
		private var responder : Responder;
		private var service : WebService;
	}

}